package com.zz.controller;

import com.zz.dto.OrderDTO;
import com.zz.exception.DataValidationException;
import com.zz.form.OrderForm;
import com.zz.service.OrderService;
import com.zz.util.OrderForm2OrderDTOConverter;
import com.zz.util.ResultVOUtil;
import com.zz.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
/**
 * Created by Bsea
 * 2019-05-6 18:30
 */
@RequestMapping("/order")
@Slf4j
@RestController
public class OrderController {

    @Resource
    OrderService orderService;
    //创建订单
    @PostMapping("/create")
    public ResultVO<Map<String, String>> create(@Valid OrderForm orderForm,
                                                BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            log.error("【创建订单】参数不正确, orderForm={}", orderForm);
            throw new DataValidationException(bindingResult.getFieldError().getDefaultMessage());
        }

        OrderDTO orderDTO = OrderForm2OrderDTOConverter.convert(orderForm);
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
            log.error("【创建订单】购物车不能为空");
            throw new DataValidationException("购物车不能为空");
        }

        OrderDTO createResult = orderService.create(orderDTO);

        Map<String, String> map = new HashMap<>();
        map.put("shopOrderId", createResult.getShopOrderId()+"");

        return ResultVOUtil.success(map);
    }
}
